package com.hhd.pdf.component.eq;

import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.component.AbstractPdfComponent;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.variable.DynamicFormula;
import com.itextpdf.text.Element;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class EqComponent extends AbstractPdfComponent {
    @Override
    public List<Element> doGenElements(GeneratorContext context) {
        org.dom4j.Element parsingElement = context.getParsingElement();
        Object var1 = getVar1(parsingElement, "var1", context);
        Object var2 = getVar1(parsingElement, "var2", context);

        if (isEqual(var1, var2))
            return genChildren(context, parsingElement);

        return CommonUtils.newList();
    }

    private static Object getVar1(org.dom4j.Element parsingElement, String var, GeneratorContext context) {
        if (CommonUtils.isEmpty(var)) return null;
        String var1Str = parsingElement.attributeValue(var);
        DynamicFormula<Object> formula = DynamicFormula.formula(var1Str, Object.class);
        context.getVariableContext().execute(formula);
        Object formulaValue = formula.getFormulaValue();
        if (CommonUtils.isEmpty(formulaValue)) return formula.getFormulaText();
        return formulaValue;
    }

    private boolean isEqual(Object var1, Object var2) {
        if (var1 == var2) return true;
        if (CommonUtils.isEmpty(var1) && !CommonUtils.isEmpty(var1)) return false;
        if (!CommonUtils.isEmpty(var1) && CommonUtils.isEmpty(var1)) return false;

        if ((var1 instanceof String ? CommonUtils.isEmpty((String) var1) : CommonUtils.isEmpty(var1))
                && (var2 instanceof String ? CommonUtils.isEmpty((String) var2) : CommonUtils.isEmpty(var2)))
            return true;

        if (var1 instanceof Number) {
            var1 = var1.toString();
        }

        if (var2 instanceof Number) {
            var2 = var2.toString();
        }

        return var1.equals(var2);
    }

    @Override
    public String getName() {
        return "eq";
    }
}
